package com.gz.mylife.im;

import java.util.List;

import net.tsz.afinal.FinalDb;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gz.mylife.Define;
import com.gz.mylife.R;
import com.gz.mylife.util.EmojiUtil;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.zl.smartmall.library.util.CrashHandler;
import com.zl.smartmall.library.util.PreferenceModel;
import com.zl.smartmall.library.util.Tools;

public class SessionAdapter extends BaseAdapter {

	private static final String TAG = "SessionAdapter";
	private List<SessionBean> mList;
	private Context mContext;
	DisplayImageOptions mOptions;
	ImageLoader mImageLoader;
	private ListView mListView;
	private int mWindowWidth;
	private View viewMenu;
	private FragmentSession.MyHandler mHandler;

	public SessionAdapter(Context context, ListView listView,
			List<SessionBean> message_list,FragmentSession.MyHandler handler) {
		mContext = context;
		mList = message_list;
		mImageLoader = ImageLoader.getInstance();
		mOptions = buildImageOptions();
		mListView = listView;
		WindowManager wm = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		mWindowWidth = wm.getDefaultDisplay().getWidth();
		this.mHandler = handler;
	}

	private DisplayImageOptions buildImageOptions() {
		return new DisplayImageOptions.Builder().resetViewBeforeLoading()
				.bitmapConfig(Bitmap.Config.ARGB_8888).cacheInMemory()
				.cacheOnDisc()
				.showStubImage(R.drawable.ic_load_image_square_default)
				.showImageForEmptyUri(R.drawable.ic_load_image_square_fail)
				.showImageOnFail(R.drawable.ic_load_image_square_fail)
				.imageScaleType(ImageScaleType.IN_SAMPLE_INT) // default
				// .displayer(new RoundedBitmapDisplayer(8))
				.build();
	}

	@Override
	public int getCount() {
		return mList.size();
	}

	@Override
	public Object getItem(int position) {
		return mList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		final ViewHolder holder;
		if (convertView == null) {
			convertView = LayoutInflater.from(this.mContext).inflate(
					R.layout.session_item, null);
			holder = new ViewHolder(convertView);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		final SessionBean bean = mList.get(position);
		if (!TextUtils.isEmpty(bean.getFace())) {
			holder.member_face_iv.setTag(bean.getGender());
			ImageLoader.getInstance().displayImage(bean.getFace(),
					holder.member_face_iv, mOptions,
					new SimpleImageLoadingListener() {
						@Override
						public void onLoadingComplete(String imageUri,
								View view, Bitmap loadedImage) {
							if (view != null && view instanceof ImageView)
								((ImageView) view).setImageBitmap(loadedImage);
						}

						@Override
						public void onLoadingFailed(String imageUri, View view,
								FailReason failReason) {
							if (view != null && view instanceof ImageView) {
//								if (bean.getGender() == 1) {
//									((ImageView) view)
//											.setImageResource(R.drawable.portrait_goatee_rounded);
//								} else {
//									((ImageView) view)
//											.setImageResource(R.drawable.portrait_lip_rounded);
//								}
								((ImageView) view).setImageResource(R.drawable.ic_load_image_square_fail);
							}
						}
					});

		} else {
//			if (bean.getGender() == 1)
//				holder.member_face_iv
//						.setImageResource(R.drawable.portrait_goatee_rounded);
//			else
//				holder.member_face_iv
//						.setImageResource(R.drawable.portrait_lip_rounded);

			holder.member_face_iv.setImageResource(R.drawable.ic_load_image_square_fail);
		}
		if (bean.getUnreadCount() > 0) {
			// 未读消息小红点
			holder.unread_iv.setVisibility(View.VISIBLE);
			if (bean.getUnreadCount() > 9) {
				holder.unread_iv.setText("9+");
			} else {
				holder.unread_iv.setText("" + bean.getUnreadCount());
			}
		} else {
			holder.unread_iv.setVisibility(View.GONE);
		}

		holder.name_tv.setText(bean.getNickname());
		holder.date_tv.setText(Tools.formatTimeStampString(mContext,
				bean.getDateline(), false));
		holder.content_tv.setText(EmojiUtil.getEmotionString(mContext,
				bean.getContent(), Tools.dip2px(mContext, 22)));
		LinearLayout.LayoutParams rlParams = (LayoutParams) holder.layout_rl
				.getLayoutParams();
		rlParams.width = mWindowWidth;

		convertView.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					if (viewMenu != null) {
						ViewHolder viewHolder1 = (ViewHolder) viewMenu.getTag();
						viewHolder1.hSView.smoothScrollTo(0, 0);
					}
					Log.d("myadapter", "MotionEvent.ACTION_DOWN");
				case MotionEvent.ACTION_UP:
					Log.d("myadapter", "MotionEvent.ACTION_UP");
					// 获得ViewHolder
					ViewHolder viewHolder = (ViewHolder) v.getTag();
					viewMenu = v;
					// 获得HorizontalScrollView滑动的水平方向值.
					int scrollX = viewHolder.hSView.getScrollX();

					// 获得操作区域的长度
					int actionW = viewHolder.action.getWidth();

					// 注意使用smoothScrollTo,这样效果看起来比较圆滑,不生硬
					// 如果水平方向的移动值<操作区域的长度的一半,就复原
					if (scrollX < actionW / 2) {
						viewHolder.hSView.smoothScrollTo(0, 0);
					} else// 否则的话显示操作区域
					{
						viewHolder.hSView.smoothScrollTo(actionW, 0);
					}
					return true;
				}
				return false;
			}
		});

		// 这里防止删除一条item后,ListView处于操作状态,直接还原
		if (holder.hSView.getScrollX() != 0) {
			holder.hSView.scrollTo(0, 0);
		}
		holder.layout_rl.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					if (viewMenu != null) {
                        ViewHolder viewHolder1 = (ViewHolder) viewMenu.getTag();
                        if(viewHolder1.hSView.getScrollX()>0 && viewHolder1 != holder){
                        	viewHolder1.hSView.smoothScrollTo(0, 0);
                        	return true;
                        }
                        if(viewHolder1.hSView.getScrollX()>0){
                        	return true;
                        }
                    }
					break;
				case MotionEvent.ACTION_UP:
					if (viewMenu != null) {
                        ViewHolder viewHolder1 = (ViewHolder) viewMenu.getTag();
                        if(viewHolder1.hSView.getScrollX()>0 && viewHolder1 == holder){
                        	viewHolder1.hSView.smoothScrollTo(0, 0);
                        	return true;
                        }
                    }
					break;

				default:
					break;
				}
				return false;
			}
		});
		holder.layout_rl.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				int count = PreferenceModel.getInt(Define.PREFERENCE_KEY_UNREAD_IM_COUNT, 0);
				count = count - bean.getUnreadCount();
				if (count > 0) {
					PreferenceModel.putInt(Define.PREFERENCE_KEY_UNREAD_IM_COUNT, count);
				} else {
					PreferenceModel.putInt(Define.PREFERENCE_KEY_UNREAD_IM_COUNT, 0);
				}
				mContext.sendBroadcast(new Intent(Define.refresh_dyncmic_unread));
				bean.setUnreadCount(0);
				FinalDb.create(mContext).update(bean);
				holder.unread_iv.setVisibility(View.GONE);
				
				Intent intent = new Intent();
				intent.setClass(mContext, ChatSession.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
				intent.putExtra("fuid", bean.getFuid());
				intent.putExtra("nickname", bean.getNickname());
				intent.putExtra("face", bean.getFace());
				intent.putExtra("gender", bean.getGender());
				mContext.startActivity(intent);
			}
		});
		holder.action.setTag(bean);
		holder.action.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				final SessionBean bean = (SessionBean) v.getTag();
				bean.setShowStatus(1);
				if(bean.getUnreadCount()>0){
					int unReadCount = PreferenceModel.getInt(Define.PREFERENCE_KEY_UNREAD_IM_COUNT, 0);
					unReadCount = unReadCount - bean.getUnreadCount();
					PreferenceModel.putInt(Define.PREFERENCE_KEY_UNREAD_IM_COUNT, unReadCount);
				}
				bean.setUnreadCount(0);
				
//				ThreadExecutor.getInstance().execute(new Runnable() {
//					
//					@Override
//					public void run() {
						SessionDao.updateShowStatus(mContext, bean);
//					}
//				});
				UpLoaderHidePmid.getInstance(mContext).upLoad(bean.getPmid());
				mList.remove(bean);
				mHandler.sendEmptyMessage(3);
				notifyDataSetChanged();
			}
		});
		CrashHandler.d(TAG, "getview position:" + position);
		return convertView;
	}

	public void updateView(int position) {
		int currIndex = position + 1;
		int visiblePosition = mListView.getFirstVisiblePosition();
		if (currIndex - visiblePosition >= 0) {
			View view = mListView.getChildAt(currIndex - visiblePosition);
			final ViewHolder holder = (ViewHolder) view.getTag();

			final SessionBean bean = mList.get(position);
			if (!TextUtils.isEmpty(bean.getFace())) {
				holder.member_face_iv.setTag(bean.getGender());
				ImageLoader.getInstance().displayImage(bean.getFace(),
						holder.member_face_iv, mOptions,
						new SimpleImageLoadingListener() {
							@Override
							public void onLoadingComplete(String imageUri,
									View view, Bitmap loadedImage) {
								if (view != null && view instanceof ImageView)
									((ImageView) view)
											.setImageBitmap(loadedImage);
							}

							@Override
							public void onLoadingFailed(String imageUri,
									View view, FailReason failReason) {
								if (view != null && view instanceof ImageView) {
//									if (bean.getGender() == 1) {
//										((ImageView) view)
//												.setImageResource(R.drawable.portrait_goatee_rounded);
//									} else {
//										((ImageView) view)
//												.setImageResource(R.drawable.portrait_lip_rounded);
//									}
									((ImageView) view).setImageResource(R.drawable.ic_load_image_square_fail);
								}
							}
						});

			} else {
//				if (bean.getGender() == 1)
//					holder.member_face_iv
//							.setImageResource(R.drawable.portrait_goatee_rounded);
//				else
//					holder.member_face_iv
//							.setImageResource(R.drawable.portrait_lip_rounded);
				holder.member_face_iv.setImageResource(R.drawable.ic_load_image_square_fail);
			}
			if (bean.getUnreadCount() > 0) {
				// 未读消息小红点
				holder.unread_iv.setVisibility(View.VISIBLE);
				if (bean.getUnreadCount() > 9) {
					holder.unread_iv.setText("9+");
				} else {
					holder.unread_iv.setText("" + bean.getUnreadCount());
				}
			} else {
				holder.unread_iv.setVisibility(View.GONE);
			}

			holder.name_tv.setText(bean.getNickname());
			holder.date_tv.setText(Tools.formatTimeStampString(mContext,
					bean.getDateline(), false));
			holder.content_tv.setText(EmojiUtil.getEmotionString(mContext,
					bean.getContent(), Tools.dip2px(mContext, 22)));

			view.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					int count = PreferenceModel.getInt(Define.PREFERENCE_KEY_UNREAD_IM_COUNT, 0);
					count = count - bean.getUnreadCount();
					if (count > 0) {
						PreferenceModel.putInt(Define.PREFERENCE_KEY_UNREAD_IM_COUNT, count);
					} else {
						PreferenceModel.putInt(Define.PREFERENCE_KEY_UNREAD_IM_COUNT, 0);
					}
					mContext.sendBroadcast(new Intent(
							Define.refresh_dyncmic_unread));
					bean.setUnreadCount(0);
					FinalDb.create(mContext).update(bean);
					holder.unread_iv.setVisibility(View.GONE);

					Intent intent = new Intent();
					intent.setClass(mContext, ChatSession.class);
					intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
					intent.putExtra("fuid", bean.getFuid());
					intent.putExtra("nickname", bean.getNickname());
					intent.putExtra("face", bean.getFace());
					intent.putExtra("gender", bean.getGender());
					mContext.startActivity(intent);
					
				}
			});

		}
	}

	static class ViewHolder {

		public ViewHolder(View view) {
			this.member_face_iv = (ImageView) view
					.findViewById(R.id.member_face_iv);
			this.name_tv = (TextView) view.findViewById(R.id.name_tv);
			this.date_tv = (TextView) view.findViewById(R.id.date_tv);
			this.content_tv = (TextView) view.findViewById(R.id.content_tv);
			this.unread_iv = (TextView) view.findViewById(R.id.unread_iv);
			this.layout_rl = (RelativeLayout) view
					.findViewById(R.id.layout_content);
			this.hSView = (HorizontalScrollView) view
					.findViewById(R.id.hsv_session);
			this.action = (RelativeLayout) view.findViewById(R.id.rl_right);
		}

		public final ImageView member_face_iv;
		public final TextView name_tv;
		public final TextView content_tv;
		public final TextView date_tv;
		public final TextView unread_iv;
		public final RelativeLayout layout_rl;
		public final HorizontalScrollView hSView;
		public final RelativeLayout action;

	}

}